package com.drdg.netty.service;

import io.netty.channel.ChannelHandlerContext;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.drdg.netty.agreement.MsgAgreement;
import com.drdg.netty.bean.InformationPacket;
import com.drdg.netty.bean.InformationPacket.Group;

public class MessageHanlderFactory {
	
	private static Map<Integer, IMessageHandler> MessageHandlers = new HashMap<Integer, IMessageHandler>();
	private final ExecutorService mScheduler = Executors.newCachedThreadPool();
	
	public void init()
	{
		MessageHandlers.clear();		
		addMassageHalder(InformationPacket.MsgEnum.CheckToLogin_VALUE, new LoginMessageHanlder());
		addMassageHalder(InformationPacket.MsgEnum.ChatOneToOne_VALUE, new ChatOneToOneMessageHanlder());
		addMassageHalder(InformationPacket.MsgEnum.ChatOneToAll_VALUE, new ChatOneToAllMessageHanlder());
		
	}
	
	private void addMassageHalder(Integer key,IMessageHandler value)
	{
		MessageHandlers.put(key, value);
	}
	
	
	public Boolean doWork(final MsgAgreement msgAgree, final ChannelHandlerContext ctx,
			final Group group)
	{		
		final IMessageHandler messageHandler = MessageHandlers.get(group.getMsgEnum().getNumber());
		if(messageHandler!=null)
		{
			 mScheduler.execute(new Runnable() {
		            public void run() {
		            	messageHandler.doWork(msgAgree, ctx, group);
		            }
		        });
			
			return true;
		}
		return false;
	}

}
